package cn.blnp.net.flowable.boot.customer.flowable.handler;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.TaskService;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.jobexecutor.TimerEventHandler;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.job.service.JobHandler;
import org.flowable.job.service.impl.persistence.entity.JobEntity;
import org.flowable.variable.api.delegate.VariableScope;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * <h3>自定义逻辑定时器</h3>
 *
 * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
 * @version 1.0
 * @since 2025/6/13 8:53
 */
@Slf4j
public class TimeoutReminderJobHandler extends TimerEventHandler implements JobHandler {

    public static final String TYPE = "timeout-reminder";

    @Override
    public String getType() {
        return TYPE;
    }

    @Override
    public void execute(JobEntity job, String configuration, VariableScope variableScope, CommandContext commandContext) {
        //获取传递给作业处理器的参数并转换为原始类型
        Map<String, String> userInfo = JSONObject.parseObject(configuration, Map.class);
        //获取工作流引擎配置
        ProcessEngineConfigurationImpl engineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
        //获取任务服务
        TaskService taskService = engineConfiguration.getTaskService();
        //查询待办任务数量
        long taskNum = taskService.createTaskQuery()
                .taskCandidateOrAssigned(userInfo.get("userId"))
                .count();
        log.info("截止 {}，{}({}) 存在 {} 个未处理工作项！", DateUtil.now(),  userInfo.get("userName"), userInfo.get("userId"), taskNum);
    }
}
